package com.example.contactcloud;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;


import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class ViewContacts extends Activity {
	
	static final String EXTRA_MESSAGE="";
	String loginStatus = "";
	private static final String PHP_DUMP = "http://softeng.cs.uwosh.edu/students/baurj00/PHPDump.php";
	private static final String PHP_LOAD = "http://softeng.cs.uwosh.edu/students/baurj00/PHPLoad.php";
	private static final String PHP_DELETE = "http://softeng.cs.uwosh.edu/students/baurj00/PHPDelete.php";
	private static final String PHP_UPDATE_CONTACT = "http://softeng.cs.uwosh.edu/students/baurj00/PHPUpdateContact.php";
	
	Contact contact = new Contact();
	
	 String oldName ="";
	String newName = "";
	
	long id = 0;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(LoginActivity.globalTheme);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_contacts);
		Intent i = getIntent();
		Contact contactWithId = (Contact)i.getSerializableExtra("Contact");
		loginStatus = i.getStringExtra(EXTRA_MESSAGE);
		ContactsDataSource cds = new ContactsDataSource(this);
		cds.open();
		contact = cds.getContactById(contactWithId.getId());
		cds.close();
		
		oldName = contact.getName();
		
		Spinner spinner = (Spinner)findViewById(R.id.groupSpinner);
		spinner.setSelection(contact.getGroup()-1,true);
		
    	EditText editText1 = (EditText)findViewById(R.id.editName);
    	EditText editText2 = (EditText)findViewById(R.id.editAddress);
    	EditText editText3 = (EditText)findViewById(R.id.editCellNum);
    	EditText editText4 = (EditText)findViewById(R.id.editAlternate);
    	EditText editText5 = (EditText)findViewById(R.id.editEmail);
    	EditText editText6 = (EditText)findViewById(R.id.editComments);
    	editText1.setText(contact.getName());
    	editText2.setText(contact.getAddress());
    	editText3.setText(contact.getCell());
    	editText4.setText(contact.getAlt());
    	editText5.setText(contact.getEmail());
    	editText6.setText(contact.getComments());
    	id = contact.getId();
    	oldName = contact.getName();
    	
    	System.out.println(id + " HEYYY" + oldName);
    	
    	
		//new GetContactTask().execute();
		new GetAllGroupsTask().execute();
		
		Button saveButton = (Button) findViewById(R.id.saveBtn);
		saveButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v){
				new putContacts().execute(contact);
				new UpdateTime().execute();

				if(loginStatus.equals("false"))
				{
					close();
				}
			}
		});
		
		//Delete button
		Button deleteBtn = (Button) findViewById(R.id.deleteBtn);
		deleteBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v){
				
				System.out.println(contact.getName() + "HEY");
				new DeleteContactTask().execute();
				
				if(loginStatus.equals("false"))
				{
					close();
				}
			}
		});
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.view_contacts, menu);
		return true;
	}
	
	private void close()
	{
		this.finish();
	}
	
	private class GetAllGroupsTask extends AsyncTask<Void, Integer, ArrayList<Group>>{

		@Override
		protected ArrayList<Group> doInBackground(Void... nothing) {
			
			ContactsDataSource cds3 = new ContactsDataSource(ViewContacts.this);
			
			cds3.open();
			
			ArrayList<Group> groups = cds3.getAllGroups();
			
			cds3.close();
			
			return groups;
		}
		
        @Override
        protected void onPostExecute(ArrayList<Group> groupList) {
    		Spinner spinner = (Spinner) findViewById(R.id.groupSpinner);
    		ArrayAdapter<Group> adapter =  new ArrayAdapter<Group>(ViewContacts.this, android.R.layout.simple_spinner_dropdown_item, groupList);
    		spinner.setAdapter(adapter);      
    		spinner.setSelection(contact.getGroup());
        }
		
	}
	
	private class UpdateTime extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			
			ContactsDataSource cds = new ContactsDataSource(ViewContacts.this);
			
			cds.open();
			
			cds.updateTime();
			
			cds.close();
			return null;
		}

		
	}
	
	//TODO if logged in, delete from cloud as well as SQLite (needs to be done in both)
	private class DeleteContactTask extends AsyncTask<Void, Integer, Contact>{

		@Override
		protected Contact doInBackground(Void... nothing) {
			
			ContactsDataSource cds2 = new ContactsDataSource(ViewContacts.this);
			
			cds2.open();
			Contact temp = contact;
			System.out.println(contact.getName() + "HEYYY");
			
        	try {
				cds2.deleteContact(contact);
				
			} catch (Exception e) {
				System.out.println("DELETE WENT WRONG");
				e.printStackTrace();
			}
			
			cds2.close();


			return temp;
		}
		protected void onPostExecute(Contact c)
		{
			if (!loginStatus.equals("false")){
				new DeleteContact().execute(c);
			}
		}
}
	
	//Delete mysql DB
	
	private class dumpMySQL extends AsyncTask<Void, Integer, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			if(networkInfo != null && networkInfo.isConnected())
			{
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_DUMP);
				
				try
				{
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String response = httpClient.execute(httppost, respondHandler);
	
				}
				catch(Exception e){
					
				}
			}
		
		return null;
	}

}
	
	
	private class putContacts extends AsyncTask<Contact, Void, Contact>{
		
		@Override
		protected Contact doInBackground(Contact... params) {
			ContactsDataSource cds2 = new ContactsDataSource(ViewContacts.this);
			
			cds2.open();
			
	    	EditText editText1 = (EditText)findViewById(R.id.editName);
	    	EditText editText2 = (EditText)findViewById(R.id.editAddress);
	    	EditText editText3 = (EditText)findViewById(R.id.editCellNum);
	    	EditText editText4 = (EditText)findViewById(R.id.editAlternate);
	    	EditText editText5 = (EditText)findViewById(R.id.editEmail);
	    	EditText editText6 = (EditText)findViewById(R.id.editComments);
	    	Spinner groupSpinner = (Spinner)findViewById(R.id.groupSpinner);
	    	
	    	int groupid = groupSpinner.getSelectedItemPosition();
	    	
	    	newName = editText1.getText().toString();
	    	
	    	contact.setName(editText1.getText().toString());
	    	contact.setAddress(editText2.getText().toString());
	    	contact.setCell(editText3.getText().toString());
	    	contact.setAlt(editText4.getText().toString());
	    	contact.setEmail(editText5.getText().toString());
	    	contact.setComments(editText6.getText().toString());
	    	contact.setGroup(groupid);
	    	
	    	System.out.println(oldName + "OLDNAME" + contact.getName() + "NewNAme");
	    	try {
	    		System.out.println("CONTACTID" + contact.getId());
				cds2.updateContact(oldName,contact);
			} catch (Exception e) {
				System.out.println("UPDATE DID NOT WORK! 0_o");
				e.printStackTrace();
			}
	    	
	    	cds2.close();
		
			return contact;
		}
		protected void onPostExecute(Contact contact)
		{
			if (!loginStatus.equals("false")){
				new UpdateCloudContact().execute(contact);
			}
			else
			{
				close();
			}
		}
	}
	
	private class DeleteContact extends AsyncTask<Contact, Void, String> 
	{
		@Override
		protected String doInBackground(Contact... arg0) 
		{
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			if(networkInfo != null && networkInfo.isConnected())
			{	
				Contact temp = arg0[0];
				String name = temp.getName();
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_DELETE);
 				
				ArrayList<NameValuePair> c = new ArrayList<NameValuePair>(1);
				c.add(new BasicNameValuePair("name", name));
				
				try
				{				
					httppost.setEntity(new UrlEncodedFormEntity(c));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String rep = httpClient.execute(httppost, respondHandler);
				}
				catch(Exception e){
					System.out.println(e.getMessage() + "FAIL2");
				}
			}
		
			return "";
		}
		protected void onPostExecute(String temp)
		{
			close();
		}
	}
	
	private class UpdateCloudContact extends AsyncTask<Contact, Void, String> 
	{
		@Override
		protected String doInBackground(Contact... arg0) 
		{
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			if(networkInfo != null && networkInfo.isConnected())
			{
				
				JSONArray allJSONContacts = new JSONArray();
				
				String all = null;

					JSONObject jContact = new JSONObject();
					Contact temp = arg0[0];
					
					try
					{
						jContact.put("id", temp.getId());
						jContact.put("name", temp.getName());
						jContact.put("address", temp.getAddress());
						jContact.put("cell", temp.getCell());
						jContact.put("alt", temp.getAlt());
						jContact.put("email", temp.getEmail());
						jContact.put("comments", temp.getComments());
						jContact.put("group", temp.getGroup());
						allJSONContacts.put(0, jContact);				
					}catch(Exception ex)
					{
						System.err.println("Cannot create #" + 0 + " JSON Contact");
					}
				
				all = allJSONContacts.toString();
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_UPDATE_CONTACT);
				
				ArrayList<NameValuePair> c = new ArrayList<NameValuePair>(1);
				c.add(new BasicNameValuePair("json", all));
				
				try
				{				
					httppost.setEntity(new UrlEncodedFormEntity(c));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String rep = httpClient.execute(httppost, respondHandler);
				}
				catch(Exception e){
					System.out.println(e.getMessage() + "FAIL1");
				}
			}
		
			return "";
		}
		protected void onPostExecute(String temp)
		{
			close();
		}
	}

}